package com.sjb.thread;

import java.util.concurrent.*;

/**
 * Created with IntelliJ IDEA.
 *
 * @Author: 有点儿意思
 * @Description:
 */
public class CyclePrint {


    private static final String THREAD_NAME = "CustomThread-";
    private static final int THREAD_COUNTER = 3;
    private static int shardCounter = 0;

    public static void main(String[] args) {
        ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(3, 3, 1000,
                TimeUnit.MILLISECONDS, new LinkedBlockingQueue<>(), runnable -> {
                    Thread thread = new Thread(runnable);
                    thread.setName(THREAD_NAME + thread.getId());
                    return thread;
                });

        String printString = "ABC";
        CyclicBarrier cyclicBarrier = new CyclicBarrier(3, () -> {
        });
        CountDownLatch countDownLatch = new CountDownLatch(THREAD_COUNTER);
        Object lock = new Object();
        Runnable runnable = new Runnable() {
            @Override
            public void run() {
                for (int i = 0; i < printString.length(); i++) {
                    synchronized (lock) {
                        shardCounter = shardCounter > 2 ? 0 : shardCounter;
                        System.out.println(printString.toCharArray()[shardCounter++]);
                    }
                    try {
                        cyclicBarrier.await();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    } catch (BrokenBarrierException e) {
                        e.printStackTrace();
                    }
                }

            }
        };
        for (int i = 0; i <THREAD_COUNTER; i++) {
            threadPoolExecutor.submit(runnable);
            countDownLatch.countDown();;
        }
        try {
            countDownLatch.await();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }finally {
            threadPoolExecutor.shutdown();
        }
    }
}
